package com.heima.wemedia.service.impl;
import com.google.common.collect.Lists;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.apis.article.IArticleClient;
import com.heima.apis.user.IUserClient;
import com.heima.common.constants.CommentComstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.comment.pojos.ApUserComment;
import com.heima.model.comment.pojos.ApUserCommentReply;
import com.heima.model.comment.vos.ApCommentRepays;
import com.heima.model.comment.vos.ApComments;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.dtos.CommentDetailsDto;
import com.heima.model.wemedia.dtos.WmCommentListDto;
import com.heima.model.wemedia.dtos.WmCommentReplyDto;
import com.heima.model.wemedia.dtos.WmCommentStatusDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.article.vos.ApArticleCommentListVo;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.*;
import com.heima.wemedia.service.WmCommentService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class WmCommentServiceImpl implements WmCommentService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmUserMapper wmUserMapper;
    @Autowired
    private IArticleClient articleClient;
    @Autowired
    private IUserClient userClient;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @Autowired
    private CacheService cacheService;


    /**
     * 回复评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult commentRepay(WmCommentReplyDto dto) {
        // 检查参数
        if (dto == null || StringUtils.isBlank(dto.getCommentId()) || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 判断当前用户是否登录
        WmUser wmUser = WmThreadLocalUtil.getUser();
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 根据评论ID，查询评论表，判断是否存在该数据
        ApUserComment apUserComment = mongoTemplate.findById(dto.getCommentId(), ApUserComment.class);
        if (apUserComment == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 根据WmUser查询APP端用户ID
        wmUser = wmUserMapper.selectById(wmUser.getId());

        // 评论回复对象
        ApUserCommentReply apUserCommentReply = new ApUserCommentReply();
        apUserCommentReply.setId(ObjectId.get());
        apUserCommentReply.setUserId(wmUser.getId());
        apUserCommentReply.setCommentId(Long.valueOf(String.valueOf(apUserComment.getId())));
        apUserCommentReply.setContent(dto.getContent());
        apUserCommentReply.setCreatedTime(new Date());
        mongoTemplate.save(apUserCommentReply);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查看评论列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findNewsComments(WmCommentListDto dto) {
        // 检查参数
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        // 判断是否登录
        WmUser wmUser = WmThreadLocalUtil.getUser();
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        dto.setApUserId(wmUser.getId());
        ResponseResult responseResult = articleClient.commentList(dto);
        Map<String, Object> data = (Map<String, Object>) responseResult.getData();
        Integer total = (Integer) data.get("total");
        List<ApArticleCommentListVo> vos = (List<ApArticleCommentListVo>) data.get("vos");
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), total);
        result.setData(vos);
        return result;
    }

    /**
     * 打开或关闭评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateCommentStatus(WmCommentStatusDto dto) {
        if (dto == null || dto.getArticleId() == null || dto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        List<ApUserComment> apUserComments = mongoTemplate.find(Query.query(Criteria.where("articleId").is(dto.getArticleId())), ApUserComment.class);
        List<ObjectId> collect = apUserComments.stream().map(ApUserComment::getId).collect(Collectors.toList());
        mongoTemplate.remove(Query.query(Criteria.where("commentId").in(collect)), ApUserCommentReply.class);
        mongoTemplate.remove(Query.query(Criteria.where("articleId").is(dto.getArticleId())), ApUserComment.class);

        // 通知article端进行文章评论状态的更改
        Map<String, Object> map = new HashMap<>();
        map.put("articleId", dto.getArticleId().toString());
        map.put("operation", dto.getOperation().toString());
        kafkaTemplate.send(CommentComstants.WM_NEWS_UPDATE_COMMENT_STATUS, JSON.toJSONString(map));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 查看文章评论的详细内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult ViewCommentDetails(CommentDetailsDto dto) {

        // 检查参数
        dto.checkParam();

        // 创建vo集合
        List<ApComments> commentsList = new ArrayList<>();

        // 按文章id 查询 所有文章的评论
        List<ApUserComment> apUserCommentList = mongoTemplate.find(Query.query(Criteria.where("articleId").is(dto.getArticleId())), ApUserComment.class);


        if (apUserCommentList != null && apUserCommentList.size() > 0) {
            for (ApUserComment apUserComment : apUserCommentList) {
                // 数据拷贝
                ApComments vo = new ApComments();
                BeanUtils.copyProperties(apUserComment, vo);

                // 手动 查询封装
                vo.setId(apUserComment.getId().toString());
                vo.setAuthorId(apUserComment.getUserId());
                vo.setEntryId(apUserComment.getArticleId());
                ApArticleConfig apArticleConfig = articleClient.findArticleConfig(dto.getArticleId());
                if (apArticleConfig != null) vo.setStatus(apArticleConfig.getIsComment());

                ApCollection apCollection = articleClient.findArticleCollectionById(dto.getArticleId());
                if (apCollection != null) vo.setType((short) apCollection.getType());

                ApArticle apArticle = articleClient.findArticle(apUserComment.getArticleId());
                if (apArticle != null) {
                    vo.setAuthorName(apArticle.getAuthorName());
                    vo.setChannelId(apArticle.getChannelId());

                    //根据作者名查 文章标记 & 作者头像
                    ApUser apUser = userClient.findUserByName(apArticle.getAuthorName());
                    if (apUser != null) {
                        vo.setFlag(apUser.getFlag());
                        vo.setImage(apUser.getImage());
                    }

                }

                // 设置评论是否点赞
                String userId = request.getHeader("userId");
                WmUser wmUser = wmUserMapper.selectById(Integer.valueOf(userId));
                String s = cacheService.get(CommentComstants.COMMENT_LIKE + wmUser.getApUserId());
                boolean status = false;
                if (StringUtils.isNotBlank(s)) {
                    List<ObjectId> list = JSON.parseArray(s, ObjectId.class);
                    if (list.contains(apUserComment.getId())) {
                        status = true;
                    }
                }

                vo.setStatus(status);

                // 暂时设置默认值
                vo.setOrd(1);
                vo.setCreatedTime(null);
                //vo.setUpdatedTime(new Date());

                List<ApCommentRepays> apCommentRepaysList = new ArrayList<>();
                // 查询每条评论的回复
                Long a = 617L;
                List<ApUserCommentReply> apUserCommentReplyList = mongoTemplate.find(Query.query(Criteria.where("commentId").is(a)), ApUserCommentReply.class);
                if (apUserCommentReplyList != null && apUserCommentReplyList.size() > 0) {

                    for (ApUserCommentReply apUserCommentReply : apUserCommentReplyList) {
                        ApCommentRepays apCommentRepaysVo = new ApCommentRepays();
                        BeanUtils.copyProperties(apUserCommentReply, apCommentRepaysVo);

                        // 手动查询封装
                        apCommentRepaysVo.setId(apUserCommentReply.getId().toString());

                        apCommentRepaysVo.setAuthorId(apUserCommentReply.getUserId());

                        ApUser apUser = userClient.findUserById(apUserCommentReply.getUserId());
                        if (apUser != null){
                            apCommentRepaysVo.setAuthorName(apUser.getName());
                        }

                        apCommentRepaysVo.setCommentId(apUserCommentReply.getCommentId().toString());
                        apCommentRepaysVo.setUpdateTime(apUserCommentReply.getCreatedTime());

                        // 回复评论添加到 回复评论集合里  apCommentRepaysList
                        apCommentRepaysList.add(apCommentRepaysVo);
                    }
                }
                // (每条)封装评论的 回复评论
                vo.setApCommentRepays(apCommentRepaysList);

                // 添加到文章的评论集合里 commentsList
                commentsList.add(vo);
            }
        }





      /*  if (true) {
            ApComments apComments = new ApComments();
            apComments.setId("1");
            apComments.setAuthorId(4);
            // apComments.setAuthorName("");
            apComments.setEntryId(1449938912930828290L);
            apComments.setChannelId(0);
            apComments.setType((short)0);
            apComments.setContent("121323212133123");
            apComments.setImage("");
            apComments.setLikes(10);
            apComments.setReply(10);
            apComments.setFlag((short)1);
            apComments.setOrd(0);

            apComments.setUpdatedTime(new Date());
            apComments.setStatus(false);
            apComments.setOperation(0);
            apComments.setApCommentRepays(Lists.newArrayList());

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());

            System.out.println("1----"+ calendar.getTimeInMillis());
            System.out.println((int) calendar.getTimeInMillis());

            long t = calendar.getTimeInMillis();


            commentsList.add(apComments);
        }*/



        // 封装
        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), commentsList.size());
        responseResult.setData(commentsList);
        return responseResult;
    }
}
